<template>
  <view class="nav-bar">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 导航栏内容 -->
    <view class="nav-bar-content">
      <!-- 返回按钮 -->
      <view class="nav-bar-left" @click="goBack" v-if="showBack">
        <u-icon name="arrow-left" color="#5C4033" size="20"></u-icon>
      </view>
      
      <!-- 标题 -->
      <view class="nav-bar-title">
        <text>{{ title }}</text>
      </view>
      
      <!-- 右侧区域(插槽) -->
      <view class="nav-bar-right">
        <slot name="right"></slot>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'NavBar',
  props: {
    title: {
      type: String,
      default: '宠物商城'
    },
    showBack: {
      type: Boolean,
      default: true
    },
    // 自定义返回函数
    customBack: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      statusBarHeight: 20 // 默认状态栏高度
    };
  },
  created() {
    // 获取系统状态栏高度
    this.getStatusBarHeight();
  },
  methods: {
    getStatusBarHeight() {
      // 获取系统信息
      uni.getSystemInfo({
        success: (res) => {
          this.statusBarHeight = res.statusBarHeight;
        }
      });
    },
    goBack() {
      // 如果有自定义返回函数，则执行
      if (this.customBack) {
        this.customBack();
        return;
      }
      
      // 获取当前页面栈
      const pages = getCurrentPages();
      
      // 如果页面栈长度大于1，说明有上一级页面，可以返回
      if (pages.length > 1) {
        uni.navigateBack({
          delta: 1
        });
      } else {
        // 如果没有上一级页面，跳转到首页
        uni.reLaunch({
          url: '/pages/shop/index'
        });
      }
    }
  }
};
</script>

<style lang="scss">
.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #FFFFFF;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .status-bar {
    width: 100%;
    background-color: #FFFFFF;
  }
  
  .nav-bar-content {
    display: flex;
    align-items: center;
    height: 90rpx;
    padding: 0 30rpx;
    
    .nav-bar-left {
      width: 80rpx;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      
      &:active {
        opacity: 0.7;
      }
    }
    
    .nav-bar-title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: 500;
      color: #5C4033;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .nav-bar-right {
      width: 80rpx;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}

// 为页面内容添加上边距，防止被导航栏遮挡
.has-nav-bar {
  padding-top: calc(90rpx + var(--status-bar-height, 20px));
}
</style> 